<template>
  <div class="connector-edit-wrap">
    <a-form-model :model="form"
                  :rules="rules"
                  ref="form"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol"
                  layout="horizontal">
      <a-form-model-item label="连接器类型"
                         prop="type">
        <a-select ref="select"
                  v-model="form.type"
                  :disabled="isDisabledCoonectorType"
                  placeholder="请选择"
                  @change="onTypeChange">
          <a-select-option :value="name"
                           :key="name"
                           v-for="(value, name) in CONNECTOR_TYPE_MAP">{{ value }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- 连接器名称 -->
      <a-form-model-item label="连接器名称"
                         prop="name">
        <a-input v-model="form.name"
                 placeholder="请输入"></a-input>
      </a-form-model-item>
      <!-- 提供方 -->
      <a-form-model-item label="提供方"
                         prop="provider"
                         help="用于标识连接器的提供方名称及业务">
        <a-input v-model="form.provider"
                 placeholder="请输入"></a-input>
      </a-form-model-item>
      <a-form-model-item label="根路径"
                         prop="baseUrl"
                         help="连接器服务的根目录名称，例：http://127.0.0.1:8080/user,'user'则是BASE_URL">
        <a-input v-model="form.baseUrl"
                 placeholder="请输入"></a-input>
      </a-form-model-item>
      <a-form-model-item label="部署节点"
                         prop="deploymentNode">
        <a-select ref="select"
                  v-model="form.deploymentNode"
                  placeholder="请选择">
          <a-select-option :value="item.deploymentNode"
                           :key="index"
                           v-for="(item, index) in deploymentNodeList">{{ item.deploymentNode }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- 验证类型 -->
      <a-form-model-item label="验证类型"
                         prop="validationType">
        <div class="flex-wrap">
          <a-select ref="select"
                    v-model="form.validationType"
                    placeholder="请选择">
            <a-select-option value="0"
                             :disabled="isMQType">无</a-select-option>
            <a-select-option value="1"
                             :disabled="isMQType">OAUTH2</a-select-option>
            <a-select-option value="2"
                             :disabled="isMQType">JWT</a-select-option>
            <a-select-option value="3">ACCOUNT</a-select-option>
            <a-select-option value="4"
                             :disabled="isMQType">自定义</a-select-option>
          </a-select>
          <!-- 只有 OAUTH2、JWT支持认证配置 -->
          <a-button type="primary"
                    v-if="!isMQType && ['1', '2', '3'].includes(form.validationType)"
                    @click="onAuthConfig">认证配置</a-button>
        </div>
      </a-form-model-item>
      <!-- ACCOUNT类型额外填写字段 -->
      <template v-if="form.validationType === '3'">
        <a-form-model-item label="USERNAME"
                           prop="userName">
          <a-input v-model="form.userName"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-form-model-item label="PASSWORD"
                           prop="password">
          <a-input v-model="form.password"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-form-model-item label="VIRTUALHOST"
                           v-if="form.type === '2'"
                           prop="virtualHost">
          <a-input v-model="form.virtualHost"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
      </template>
      <template v-if="form.validationType === '4'">
        <a-form-model-item label="类名"
                           prop="className">
          <a-input v-model="form.className"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
      </template>
      <a-form-model-item label="描述"
                         prop="detail">
        <a-textarea v-model="form.detail"
                    placeholder="请输入"></a-textarea>
      </a-form-model-item>

      <div style="text-align:center">
        <ZOkButton @click="onSave('form')"></ZOkButton>
      </div>
    </a-form-model>
  </div>
</template>

<script>
import { fetchDeploymentNodeList, saveOrUpdateConnector, fetchConnectorInfo } from '../../../api/connector-manage'
import { CONNECTOR_TYPE_MAP } from '../config'
import { sendBeforeHandle } from '../server'
export default {
  name: 'ConnectorEdit',
  props: {
    parentNode: {
      type: Object,
      default: () => null
    },
    authConfigData: {
      type: Object,
      default: () => {
        return {
          form: {},
          requestTableData: {
            params: [],
            header: [],
            path: []
          },
          responeTableData: []
        }
      }
    }
  },
  data () {
    return {
      connectorData: null,
      labelCol: { span: 6 },
      wrapperCol: { span: 12 },
      CONNECTOR_TYPE_MAP: CONNECTOR_TYPE_MAP,
      form: {
        id: '',
        type: '1',
        name: '',
        baseUrl: '',
        provider: '',
        validationType: '0',
        deploymentNode: '',
        userName: undefined,
        password: undefined,
        virtualHost: undefined,
        className: undefined,
        detail: undefined
      },
      rules: {
        type: [{
          required: true, message: '请选择类型', trigger: 'change'
        }],
        name: [{
          required: true, message: '请输入名称', trigger: 'blur'
        }],
        provider: [{
          required: true, message: '请输入提供方', trigger: 'blur'
        }],
        baseUrl: [{
          required: true, message: '请输入根路径', trigger: 'blur'
        }],
        userName: [{
          required: true, message: '请输入', trigger: 'blur'
        }],
        password: [{
          required: true, message: '请输入', trigger: 'blur'
        }],
        virtualHost: [{
          required: true, message: '请输入', trigger: 'blur'
        }],
        className: [{
          required: true, message: '请输入', trigger: 'blur'
        }]
      },
      deploymentNodeList: []
    }
  },
  created () {
    this.getDeploymentNodeList()
  },
  computed: {
    // 判断是否属于MQ类型连接器
    isMQType: function () {
      return ['2', '3', '4'].includes(this.form.type)
    },
    // 连接器无法修改类型
    isDisabledCoonectorType: function () {
      return !!this.form.id
    }
  },
  watch: {
    parentNode: {
      handler: function (newNode) {
        if (newNode) {
          if (!newNode.isCache) {
            if (newNode.showRightType === 'CONNECTOR' && !newNode.isAdd) {
              this.getConnectorInfo(newNode.id)
            } else {
              this.form = {
                id: '',
                type: '1',
                name: '',
                baseUrl: '',
                provider: '',
                validationType: '0',
                deploymentNode: '',
                userName: undefined,
                password: undefined,
                virtualHost: undefined,
                className: undefined,
                detail: undefined
              }
              this.form.interfaceAndParamterVo = {}
            }
          }
        }
      },
      deep: true
    },
    authConfigData: {
      handler: function (newData) {
        this.connectorData = newData
      },
      deep: true
    }
  },
  methods: {
    // 获取部署节点下拉列表
    async getDeploymentNodeList () {
      const res = await fetchDeploymentNodeList()
      this.deploymentNodeList = res || []
    },
    async getConnectorInfo (id) {
      const res = await fetchConnectorInfo(id)
      this.form = { ...res }
      const interfaceAndParamterVo = this.form.interfaceAndParamterVo
      this.connectorData = {
        form: interfaceAndParamterVo?.connectorInterfaceVo,
        requestTableData: {
          params: interfaceAndParamterVo?.connectorInterfaceVo.requestMethod === '1' ? interfaceAndParamterVo?.requestParamterVo.getParamters : interfaceAndParamterVo?.requestParamterVo.paramterDataVoRequestList,
          headers: interfaceAndParamterVo?.requestParamterVo.headers,
          paths: interfaceAndParamterVo?.requestParamterVo.path
        },
        responeTableData: interfaceAndParamterVo?.responseParamterVo.paramterDataVoResponseList
      }
    },
    // 认证配置操作
    onAuthConfig () {
      this.$emit('authConfig', {
        ...this.form,
        showType: 'AUTH'
      })
    },
    onTypeChange () {
      this.form.validationType = this.isMQType ? '3' : '0'
    },
    onSave (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 过滤掉参数字段为空的数据
          const requestParams = sendBeforeHandle(this.connectorData?.requestTableData?.params || [])
          const requestHeader = sendBeforeHandle(this.connectorData?.requestTableData?.header || [])
          const requestPath = this.connectorData?.requestTableData?.path || []
          const responeTableData = sendBeforeHandle(this.connectorData?.responeTableData || [])
          const connectorDataForm = this.connectorData ? { ...this.connectorData.form } : {}
          const params = {
            ...this.form,
            pid: this.parentNode.isAdd ? this.parentNode.id : this.form.pid,
            interfaceAndParamterVo: {
              connectorInterfaceVo: connectorDataForm,
              // 请求解析后参数
              requestParamterVo: {
                ...connectorDataForm.requestMethod == '1' ? { getParamters: requestParams } : { paramterDataVoRequestList: requestParams },
                headers: requestHeader,
                paths: requestPath
              },
              // 响应解析后参数
              responseParamterVo: {
                paramterDataVoResponseList: responeTableData
              }
            }
          }
          if (['1', '2', '3'].includes(this.form.validationType)) {
            // 选择了认证配置，认证接口name和interfaceType设置为固定值
            params.interfaceAndParamterVo.connectorInterfaceVo.name = `${this.form.name}认证`
            params.interfaceAndParamterVo.connectorInterfaceVo.interfaceType = '2'
          } else {
            // 选择了其他认证类型，清空认证接口参数信息
            delete params.interfaceAndParamterVo
          }
          saveOrUpdateConnector(params).then(() => {
            this.$emit('sucess')
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.connector-edit-wrap {
  .flex-wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
  }
}
</style>